package com.atguigu.gmall.order.listener;/*
 * @author: XueYouPeng
 * @time: 23.8.1 下午 8:52
 */

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.rabbit.constant.RabbitConstant;
import com.atguigu.gmall.rabbit.service.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
public class OrderPayedListener {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(queues = RabbitConstant.ORDER_PAYED_QUEUE)
    public void orderPayedListener(Message message , Channel channel){

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        byte[] body = message.getBody();
        //body转换成JSON
        String msgJSON = new String(body);

        try {
            Map<String , String> params = JSON.parseObject(msgJSON, Map.class);
            orderInfoService.updateOrderStatusPayed(params) ;
            log.info("支付成功以后，修改了订单的状态...");
            channel.basicAck(deliveryTag,true);
        } catch (IOException e) {
            e.printStackTrace();
            rabbitService.retry(channel,deliveryTag,msgJSON,5);
        }
    }
}
